<?php

namespace App\Http\Controllers;

use App\Models\Car;
use App\Models\Member;
use App\Models\Message;
use App\Models\MyCar;
use App\Models\MyStage;
use App\Models\Parking;
use App\Models\Record;
use App\Models\UserLotteryLog;
use App\Repos\CarRepo;
use App\Repos\MemberRepo;
use App\Repos\MessageRepo;
use App\Transformers\CarTransformer;
use App\Transformers\MemberTransformer;
use App\Transformers\MessageTransformer;
use App\Transformers\ParkingTransformer;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class ParkInfoController extends ApiController
{
    protected $memberRepo;
    public function __construct(MemberRepo $memberRepo)
    {
        parent::__construct();
        $this->memberRepo = $memberRepo;
    }

    //综合
    public function index()
    {
        $uid = $this->user->id;
    
        //用户信息
        $member = $this->memberRepo->find($uid);
        
        $memberTransformer = new MemberTransformer();
        $userInfo = $memberTransformer->singleData($this->user);
        
        //好友列表
        $friends=$member->setRemoteFollow()->friendsList($this->user->id);
    
        //消息列表
        $message = Message::where('to_user_id',$this->user->id)->where('type','<',3)->take(4)->orderByDesc('id')->get();
        $messages = (new MessageTransformer())->listData($message);
    
        //广告
        //$index_ad_config = config('car.index_ad');
        //$adInfo = $index_ad_config['thumb'] ? $index_ad_config : null;
        $adInfo = null;
    
        //每分钟只执行一次
        $cache_name = 'park_index_autoback';
        if(!Cache::has($cache_name)){
            Cache::put($cache_name,1,1);
            //自动判断收车
            $this->autoBackAllCar();
        }
        
        //我的车位
        $parking = Parking::where('user_id',$this->user->id)->orderBy('id')->get();
        $parkings = (new ParkingTransformer())->listData($parking);
    
        //如果车是自己的，才显示道具
        foreach ($parkings as &$park) {
            if(!empty($park['car']) && $park['car']['items']){
                if($this->user->id != $park['car']['owner']['id']){
                    $park['car']['items'] = [];
                }
            }
        }
    
        //我的车辆
        $cars = (new CarRepo())->myCars($this->user);
        
        //陌生人
        $strangers=$this->memberRepo->randomStrangerUsers($this->user->id,5);
    
        $lottery_log = UserLotteryLog::where('user_id',$this->user->id)->first();
        if(!empty($lottery_log) && $lottery_log['lottery_id'] == 1){
            $first_login = 0;
        }else{
            $first_login = 1;
            if(!$lottery_log){
                $lottery_log = new UserLotteryLog();
                $lottery_log->user_id = $this->user->id;
                $lottery_log->gold_num = 0;
            }
            $lottery_log->lottery_id = 1;
            $lottery_log->save();
        }
        
        
        $gift_car=[];
        $new_car_config = config('car.cfgStopLimit.CarForNewUser');
        if($new_car_config){
            if($car = Car::find($new_car_config)){
                $gift_car = (new CarTransformer())->singleData($car);
            }
        }
        
        return $this->success(compact('userInfo','friends','messages','adInfo','parkings','cars','strangers','first_login','gift_car'));
    }
    
    //自动收所有车
    public function autoBackAllCar()
    {
        //自动收车优化选择
        Record::orderBy('ParkStartTime')->get()->map(function($record){
            $myCar = MyCar::find($record->myCarID);
            if(!$myCar)
                return false;
    
            $carRepo = new CarRepo();
            $carRepo->countStatus($myCar);
            $user = Member::find($myCar->uid);
            $car = Car::find($myCar->CarID);
    
            $stop_min = Carbon::now()->diffInMinutes(Carbon::parse($record->ParkStartTime));
            $diff_min = $stop_min - $carRepo->max_stop_time;
            //如果停车时间超过了最大停车时间
            if($diff_min > 0) {
                $record = Record::where('ParkUid',$user->id)->where('myCarID',$myCar->ID)->firstOrFail();
                $parking = Parking::find($record->Parklot);
                
                $punishedCredit = $carRepo->current_income ?: 0;
    
                if ($carRepo->status == 3) {
                    $punisherCredit = floor($carRepo->current_income * config('car.cfgStopLimit.PunisherPersent') / config('car.cfgStopLimit.PunishedPersent'));
                    $this->memberRepo->incrementUserCredit(Member::find($record->ParkWhoUid),$punisherCredit);
        
                    MessageRepo::push([
                        'type'       => 1,
                        'user_id'    => $user->id,
                        'to_user_id' => $record->ParkWhoUid,
                        'text'       => sprintf(config('words.messages.back_other_car_punished'),$parking->user->nickname,$punisherCredit),
                        'record_id'  => $record->RID,
                    ]);
                }
    
                $this->memberRepo->incrementUserCredit($user,$punishedCredit);
                MessageRepo::push([
                    'type'       => 1,
                    'user_id'    => $user->id,
                    'to_user_id' => $user->id,
                    'text'       => sprintf(config('words.messages.back_my_car'),$user->nickname,$parking->user->nickname,$punishedCredit),
                    'record_id'  => $record->RID,
                ]);
    
                MessageRepo::push([
                    'type'=>1,
                    'user_id'=>$this->user->id,
                    'to_user_id'=>$record->ParkWhoUid,
                    'text'=>sprintf(config('words.messages.back_other_car'),
                        $this->user->nickname,
                        $car->CarName,
                        Member::find($record->ParkWhoUid)->nickname,
                        Carbon::parse($record->ParkStartTime)->diffForHumans(null,true),
                        $punishedCredit
                    ),
                    'record_id'=>$record->RID,
                ]);
                
                $record->ParkStartTime = Carbon::now()->toDateTimeString();
                $record->ParkStatus = 0;
                $record->ParkPunish = 0;
                $record->Parklot = 0;
                $record->ParkWhoUid = 0;
                $record->save();
                //将此车的所有道具状态改为已使用
                MyStage::where('car_id',$myCar->ID)->update(['status'=>1]);
            }
            return true;
        });
        
        
    }
    
    //车位列表
    public function parkingList($user_id=0,MemberRepo $memberRepo)
    {
        $user_id=$user_id?:$this->user->id;
        
        $list = Parking::where('user_id',$user_id)->orderBy('id')->get();
        
        $parkings = (new ParkingTransformer())->listData($list);
    
        foreach ($parkings as &$parking) {
            if(!empty($parking['car'])){
                $parking['car']['is_mine']=(int)($this->user->id == $parking['car']['owner']['id']);
    
                if($parking['car']['items'] && !$parking['car']['is_mine']){
                        $park['car']['items'] = [];
                }
            }
        }
        
        $parking_owner=$memberRepo->find($user_id)->info();
    
        $member = $this->memberRepo->find($user_id);
        //好友列表
        $friends=$member->friendsList($this->user->id);
    
        //消息列表
        $message = Message::where('to_user_id',$this->user->id)->where('type','<',3)->take(4)->orderByDesc('id')->get();
        $messages = (new MessageTransformer())->listData($message);
    
        //陌生人
        $strangers=$this->memberRepo->randomStrangerUsers($this->user->id,5);
        
        return $this->success(compact('parking_owner','parkings','friends','strangers','messages'));
    }
    
    //升级车位
    public function upgrade()
    {
        $parking_id = $this->request->parking_id;
        $parking = Parking::findOrFail($parking_id);
        
        //车位上不能有其它车辆
        if($parking->record){
            return $this->error(1,'车位上没有其他车辆时可以对停车位进行升级');
        }
        
        if($parking->type < 3){
            if($parking->type == 1){
                $upgrade_gold = config('car.cfgStopLimit.upgradeParkingPrivate');
            }elseif($parking->type == 2){
                $upgrade_gold = config('car.cfgStopLimit.upgradeParkingCharge');
            }
            //检查用户余额是否足够
            if($this->user->getCredit() < $upgrade_gold){
                return $this->error(1,'用户余额不足以升级');
            }
    
            //扣除用户余额
            $decreUser = MemberRepo::decrementUserCredit($this->user,$upgrade_gold);
            
            $parking->type++;
            $parking->save();
            MessageRepo::push([
                'type'=>2,
                'user_id'=>$this->user->id,
                'to_user_id'=>$this->user->id,
                'text'=>sprintf(config('words.messages.upgrade_parking'),$parking->type_text_chinese),
                'record_id'=>0,
            ]);
            return $this->success('升级成功');
        }
        
        return $this->error(1,'已达最大等级');
        
    }
    

    
}
